package com.jdone.compus.controller;

import com.jdone.compus.dto.ApiResponse;
import com.jdone.compus.model.BlowAnnouncement;
import com.jdone.compus.service.BlowAnnouncementService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/blow/announcements")
@Api(value = "吹风公告管理", tags = "吹风公告管理")
public class BlowAnnouncementController {

    @Autowired
    private BlowAnnouncementService service;

    @ApiOperation("新增公告")
    @PostMapping("/end_back/add")
    public ApiResponse add(@RequestBody BlowAnnouncement dto) {
        return ApiResponse.success(service.create(dto));
    }

    @ApiOperation("根据ID查询公告")
    @GetMapping("/end_back/find/{id}")
    public ApiResponse getById(@PathVariable Long id) {
        try {
            return ApiResponse.success(service.getById(id));
        } catch (RuntimeException ex) {
            return ApiResponse.error(ex.getMessage());
        }
    }

    @ApiOperation("分页查询公告列表")
    @GetMapping("/end_back/findAll")
    public ApiResponse list(@RequestParam int page, @RequestParam int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<BlowAnnouncement> pageResult = service.getAll(pageable);
        return ApiResponse.success(pageResult);
    }

    @ApiOperation("修改公告")
    @PutMapping("/end_back/update/{id}")
    public ApiResponse update(@PathVariable Long id,
                              @RequestBody BlowAnnouncement dto) {
        try {
            return ApiResponse.success(service.update(id, dto));
        } catch (RuntimeException ex) {
            return ApiResponse.error(ex.getMessage());
        }
    }

    @ApiOperation("删除公告")
    @DeleteMapping("/end_back/delete/{id}")
    public ApiResponse delete(@PathVariable Long id) {
        try {
            service.delete(id);
            return ApiResponse.success("删除成功");
        } catch (RuntimeException ex) {
            return ApiResponse.error(ex.getMessage());
        }
    }

    @ApiOperation("微信端：查询当前启用的公告")
    @GetMapping("/wechat/findEnabled")
    public ApiResponse getEnabled() {
        try {
            BlowAnnouncement enabled = service.getEnabledAnnouncement();
            return ApiResponse.success(enabled);
        } catch (RuntimeException ex) {
            return ApiResponse.error(ex.getMessage());
        }
    }
}

